﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;

namespace FolderTransfer
{
    public class Utils
    {
        private Utils() { }

        /// <summary>
        /// 随机数产生对象
        /// </summary>
        public static Random random = new Random();

        /// <summary>
        /// 计时器
        /// </summary>
        public static Stopwatch watch = new Stopwatch();

        /// <summary>
        /// 获取本机的IPV4地址
        /// </summary>
        public static IPAddress GetHostIP()
        {
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in ips)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    return ip;
            }
            return ips[0];
        }

        /// <summary>
        /// 获取本机的IPV4地址
        /// </summary>
        public static void PrintAllip()
        {
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in ips)
            {
                Console.WriteLine(ip.ToString());
            }
        }

        /// <summary>
        /// 获取一个本机可用的端口号
        /// </summary>
        public static int GetAvailablePort()
        {
            int port;
            TcpListener testListener;
            while (true)
            {
                port = random.Next(1024, 5000);
                try
                {
                    testListener = new TcpListener(GetHostIP(), port);
                    testListener.Start();
                }
                catch
                {
                    continue;
                }
                testListener.Stop();
                return port;
            }
        }

        public static String GetSpeed(long totalLen, long ms)
        {
            long speed = totalLen * 1000 / 1024 / 1024 / ms;
            return speed + " M/S";
        }

        public static String GetTime(long ms)
        {
            if (ms / 1000 == 0)
            {
                return "1 秒钟";
            }
            else 
            {
                long fs = ms / 1000 / 60;
                if (fs >= 1L)
                {
                    return fs + " 分钟";
                }
                else
                {
                    return ms / 1000 + "秒钟";
                }
            }
        }
        
    }
}
